package com.dd.machine.main.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.dd.machine.base.app.MyApplication;
import com.dd.machine.greendao.gen.AppAdverDao;
import com.dd.machine.greendao.gen.AppGoodsKindDao;
import com.dd.machine.main.commons.SPUtils;
import com.dd.machine.main.user.model.AppAdver;
import com.dd.machine.main.user.model.AppGoodsKind;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.greendao.query.Query;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import java.text.SimpleDateFormat;

import okhttp3.Call;

import static com.dd.machine.base.net.URLManager.APPCONFIG;

/**
 * Created by Administrator on 2017/6/29.
 */

public class PollingService extends Service{
    private Context context;
    public static final String ACTION = "com.dd.machine.main.service.PollingService";
    int count = 0;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        context = getApplicationContext();
        new PollingThread().start();

        return super.onStartCommand(intent, flags, startId);
    }

    class PollingThread extends Thread{
        @Override
        public void run() {
            Log.e("--system","polling");
            getData();
        }
    }

    private void getData() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Log.e("===service","===resuest");
        Log.e("===执时间以及次数","次数："+count+"时间" +sdf.format(System.currentTimeMillis()));
        count++;
        OkHttpUtils.post()
                .url(APPCONFIG)
                .addParams("platform","android")
                .addParams("equipmentNo","JINANDINGGAO")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (count<3) {//设置如果轮询中失败，再重复执行一次，反复不超过三次。
                            getData();
//                            count++;
                        }else {
                            Intent localIntnet = new Intent("PollingService");
                            LocalBroadcastManager.getInstance(context).sendBroadcast(localIntnet);
                        }

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("===response",response);

                        json2List(response);
                    }
                });
    }
    private void json2List(String response) {
        try {
            JSONObject object = new JSONObject(response);
            JSONArray jsonArray = object.optJSONArray("app_fix_price");
            JSONArray array = object.optJSONArray("app_adver");
            String qrCode  = object.optString("app_wechat_bar_code");
            Log.e("===qrcode",qrCode);
            SPUtils.setQRCode(this,qrCode);
            AppGoodsKind kind;
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.optJSONObject(i);
                kind = new AppGoodsKind();
                kind.setGoodsId(jsonObject.optInt("id"));
                kind.setAreaId(jsonObject.optInt("areaId"));
                kind.setImg(jsonObject.optString("img"));
                kind.setTypeName(jsonObject.optString("typeName"));
                if ((jsonObject.opt("parentId")+"").equals("null")) {
                    kind.setParentId("no");
                }else {
                    kind.setParentId(jsonObject.opt("parentId")+"");
                }
                kind.setCreateTime(jsonObject.optLong("createTime"));
                kind.setUnitPrice(jsonObject.optDouble("unitPrice"));
                kind.setUpdateTime(jsonObject.optLong("updateTime"));
                kind.setDisable(jsonObject.optInt("disable"));
                kind.setSequence(jsonObject.optInt("sequence"));
                kind.setUpdateBy(jsonObject.optInt("updateBy"));
                cacheAppInfo(kind);

            }
            for (int i = 0; i < array.length(); i++) {
                JSONObject object1 = array.getJSONObject(i);
                AppAdver appAdver = new AppAdver();
                appAdver.setAdvId(i+1);
                appAdver.setImgUrl(object1.optString("imgUrl"));
                appAdver.setGotoUrl(object1.optString("gotoUrl"));
                appAdver.setSequence(object1.optInt("sequence"));
                cacheAdvInfo(appAdver);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        Intent localIntnet = new Intent("PollingService");
        LocalBroadcastManager.getInstance(context).sendBroadcast(localIntnet);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    public void cacheAppInfo(AppGoodsKind kind){
        AppGoodsKind old = getInfoFromCache(kind.getGoodsId()+"");
        if (old!=null) {
            kind.setId(old.getId());
        }
        AppGoodsKindDao appDao = MyApplication.getInstances().getDaoSession().getAppGoodsKindDao();
        appDao.save(kind);

    }
    public void cacheAdvInfo(AppAdver appAdver){
        AppAdver old = getAdvInfoFromCache(appAdver.getAdvId()+"");
        if (old!=null) {
            appAdver.setId(old.getId());
        }
        AppAdverDao dao = MyApplication.getInstances().getDaoSession().getAppAdverDao();
        dao.save(appAdver);
    }

    public AppAdver getAdvInfoFromCache(String id){
        AppAdverDao userDao = MyApplication.getInstances().getDaoSession().getAppAdverDao();
        Query<AppAdver> query = userDao.queryBuilder().where(AppAdverDao.Properties.AdvId.eq(id))
                .orderDesc(AppAdverDao.Properties.AdvId).build();
        return query.unique();

    }
    public AppGoodsKind getInfoFromCache(String memberId) {
        AppGoodsKindDao userDao = MyApplication.getInstances().getDaoSession().getAppGoodsKindDao();
        Query<AppGoodsKind> query = userDao.queryBuilder().where(AppGoodsKindDao.Properties.GoodsId.eq(memberId))
                .orderDesc(AppGoodsKindDao.Properties.GoodsId).build();
        return query.unique();
    }
}
